from rest_framework import serializers
import datetime, logging, requests, re, json
from decimal import Decimal
from django.db import transaction
from django_redis import get_redis_connection
from equity_mall.utils.qiniu_storage import pic_upload
from django.db.models import Count, Sum, Max, Min, Avg
from random import randint
from PIL import Image
import io

from equity_admin.filters_vouchers import *
from users.models import *
from goods.models import *
from activities.models import *
from postallive.models import *
from merchants.models import *
from cashbonus.models import *
from equity_mall.utils.utils import redis_scheme_token_wyh, check_sign_contract_result, get_sign_contract_url
from equity_mall.utils.sync_img_to_local import make_qrcode1

logger = logging.getLogger('django')


class LevelListSerializer(serializers.ModelSerializer):

    class Meta:
        model = Level
        fields = ('id', 'prov_name', 'city_name', 'district_name', 'branch_name', 'orgId', 'account', 'account_nine', 'level')


class LevelModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = Level
        fields = ['id', 'prov_name', 'city_name', 'district_name', 'branch_name']


class AliDiscountCouponListModelSerializer(serializers.ModelSerializer):

    coupon_type_str = serializers.CharField(source='get_coupon_type_display', read_only=True)
    coupon_status_str = serializers.CharField(source='get_coupon_status_display', read_only=True)
    coupon_way_str = serializers.CharField(source='get_coupon_way_display', read_only=True)
    publish_time = serializers.SerializerMethodField(read_only=True)
    coupon_status = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    distribution_platform_str = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCoupon
        fields = ['id', 'coupon_type', 'coupon_type_str', 'activity_name', 'coupon_status', 'coupon_status_str', 'floor_amount',
                  'publish_time', 'max_number', 'send_count', 'remain_number', 'coupon_way', 'coupon_way_str', 'template_id', 'level_name',
                  'distribution_platform_id', 'distribution_platform_str']

    def get_distribution_platform_str(self, obj):
        try:
            return obj.distribution_platform.platform_name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_coupon_status(self, obj):
        try:
            now_date = datetime.datetime.now()
            if obj.coupon_status in [1, 4]:
                if obj.publish_end_time < now_date:
                    obj.coupon_status = 2
                    obj.save()
                    return 2
            # elif obj.coupon_status == 3:
            #     if obj.publish_start_time < now_date:
            #         obj.coupon_status = 1
            #         obj.save()
            #         return 1
            return obj.coupon_status
        except:
            return obj.coupon_status

    def get_publish_time(self, obj):
        try:
            return f'{obj.publish_start_time.strftime("%Y.%m.%d %H:%M:%S")}-{obj.publish_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
        except:
            return ''

'''代金券活动客管-序列化功能'''
class AliDiscountCouponKeGuanListModelSerializer(serializers.ModelSerializer):
    push_status_str = serializers.CharField(source='get_push_status_display', read_only=True)
    push_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_no = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponInfoKeguan
        fields = ['id', 'push_status_str', 'push_status', 'push_time', 'return_msg', 'alidiscountcouponinfo_id',
                  'payment_no']

    def get_payment_no(self, obj):
        try:
            return obj.alidiscountcouponinfo.out_biz_no
        except:
            return ''


class AliDiscountCouponChannelCommonVoucherModelSerializer(serializers.ModelSerializer):

    discount_type_str = serializers.CharField(source='get_discount_type_display', read_only=True)
    bankcard_type_str = serializers.CharField(source='get_bankcard_type_display', read_only=True)
    usetime_type = serializers.SerializerMethodField(read_only=True)
    join_limit_by_user = serializers.SerializerMethodField(read_only=True)
    join_limit_by_bay = serializers.SerializerMethodField(read_only=True)
    distributed_limit_by_time_rules = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponChannelCommonVoucher
        fields = ['id', 'discount_type', 'discount_type_str', 'bankcard_type', 'bankcard_type_str', 'usetime_type', 'principal_name',
                  'join_limit_by_user', 'join_limit_by_bay', 'distributed_limit_by_time', 'distributed_limit_by_time_rules']

    def get_distributed_limit_by_time_rules(self, obj):
        data = []
        try:
            alidiscountcoupondistributedlimit_set = obj.alidiscountcoupondistributedlimit_set.all()
            for alidiscountcoupondistributedlimit in alidiscountcoupondistributedlimit_set:
                week_day_dict = {
                    '0': '周一',
                    '1': '周二',
                    '2': '周三',
                    '3': '周四',
                    '4': '周五',
                    '5': '周六',
                    '6': '周日',
                }
                weeks = ''
                for key,value in week_day_dict.items():
                    if key in alidiscountcoupondistributedlimit.weeks:
                        weeks += f'、{value}'
                data.append({
                    "weeks": f'每周 {weeks[1:]}',
                    "enable_time": f'{alidiscountcoupondistributedlimit.start_enable_time.strftime("%H:%M:%S")}-{alidiscountcoupondistributedlimit.end_enable_time.strftime("%H:%M:%S")}'
                })
        except:
            pass
        return data

    def get_usetime_type(self, obj):
        try:
            if obj.usetime_type == 2:
                return f'固定时间段{obj.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{obj.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
            elif obj.usetime_type == 3:
                return f'领取后立即生效有效时间{obj.invalid_day}天'
            else:
                return f'领取后次日凌晨生效有效时间{obj.invalid_day}天'
        except:
            return ''

    def get_join_limit_by_user(self, obj):
        try:
            if obj.join_limit_by_user == 1:
                return f'活动期间每个用户可参与{obj.join_limit_by_user_count}次'
            else:
                return '不限制'
        except:
            return ''

    def get_join_limit_by_bay(self, obj):
        try:
            if obj.join_limit_by_bay == 1:
                return f'每个用户每日可参与{obj.join_limit_by_bay_count}次'
            elif obj.join_limit_by_bay == 2:
                return f'每个用户每月可参与{obj.join_limit_by_bay_count}次'
            elif obj.join_limit_by_bay == 4:
                return f'每个用户每周可参与{obj.join_limit_by_bay_count}次'
            else:
                return '不限制'
        except:
            return ''


class AliDiscountCouponRetrieveModelSerializer(serializers.ModelSerializer):

    coupon_type_str = serializers.CharField(source='get_coupon_type_display', read_only=True)
    coupon_status_str = serializers.CharField(source='get_coupon_status_display', read_only=True)
    coupon_way_str = serializers.CharField(source='get_coupon_way_display', read_only=True)
    publish_time = serializers.SerializerMethodField(read_only=True)
    alidiscountcouponchannelcommonvoucher = AliDiscountCouponChannelCommonVoucherModelSerializer()
    level = LevelModelSerializer()
    merchant_list = serializers.SerializerMethodField(read_only=True)
    platform = serializers.SerializerMethodField(read_only=True)
    can_remain_number = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    publish_start_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    publish_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    last_update_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    developer_set = serializers.SerializerMethodField(read_only=True)
    create_user = serializers.SerializerMethodField(read_only=True)
    distribution_platform = serializers.SerializerMethodField(read_only=True)
    drawdown_platform = serializers.SerializerMethodField(read_only=True)
    is_max_number_by_day = serializers.SerializerMethodField(read_only=True)
    wyh_last_update_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_check_identity = serializers.SerializerMethodField(read_only=True)
    ysh_alidiscountcoupon = serializers.SerializerMethodField(read_only=True)
    activity_zone_qrcode = serializers.SerializerMethodField(read_only=True)
    usage_scenario_str = serializers.CharField(source='get_usage_scenario_display', read_only=True)

    class Meta:
        model = AliDiscountCoupon
        fields = ['id', 'coupon_type', 'coupon_type_str', 'activity_name', 'coupon_status', 'coupon_status_str', 'floor_amount',
                  'publish_time', 'max_number', 'send_count', 'remain_number', 'alidiscountcouponchannelcommonvoucher', 'level',
                  'is_union', 'is_white', 'available_merchants', 'coupon_way', 'coupon_way_str', 'activity_description', 'merchant_list',
                  'create_time', 'template_id', 'platform', 'publish_end_time', 'publish_start_time', 'transaction_minimum', 'amount',
                  'is_need_auth', 'can_remain_number', 'developer_set', 'last_update_time', 'create_user', 'remark', 'distribution_platform',
                  'distribution_platform_id', 'wyh_last_update_time', 'goods_tag', 'drawdown_platform', 'drawdown_platform_id', 'is_use_path', 'use_path', 'use_appid',
                  'is_self', 'max_number_by_day', 'is_max_number_by_day', 'is_check_identity', 'ysh_alidiscountcoupon', 'banner_long', 'banner_short',
                  'activity_zone_qrcode', 'is_psbc_card', 'product_no', 'is_keguan', 'pushEventIds', 'usage_scenario', 'usage_scenario_str']

    def get_is_use_path(self, obj):
        try:
            if obj.is_use_path:
                return obj.is_use_path
            else:
                return 0
        except:
            return 0

    def get_is_self(self, obj):
        try:
            if obj.is_self:
                return obj.is_self
            else:
                return 0
        except:
            return 0

    def get_activity_zone_qrcode(self, obj):
        try:
            if obj.coupon_channel == 2 and obj.goods_tag:
                if not obj.activity_zone_qrcode:
                    redis_conn = get_redis_connection("scheme")
                    access_token = redis_conn.get('wyh_access_token')
                    if access_token is None:
                        access_token = redis_scheme_token_wyh()
                    else:
                        access_token = access_token.decode()
                    url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
                    body = {
                        "page": "pages/coupon_pro_list/coupon_pro_list",
                        "scene": f"activity_id={obj.id}",
                        "is_hyaline": True
                    }
                    response = requests.post(url=url, json=body)
                    try:
                        if response.json()['errcode'] != 0:
                            access_token = redis_scheme_token_wyh()
                            url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
                            response = requests.post(url=url, json=body)
                    except:
                        pass
                    reslut = response.content
                    activity_zone_qrcode = pic_upload(reslut)
                    obj.activity_zone_qrcode = activity_zone_qrcode
                    obj.save()
                    return f'https://circle.sutpay.cn/{activity_zone_qrcode}'
                else:
                    return obj.activity_zone_qrcode.url
            else:
                return ''
        except:
            return ''

    def get_ysh_alidiscountcoupon(self, obj):
        data = {}
        try:
            ysh_alidiscountcoupon = YSHAliDiscountCoupon.objects.filter(alidiscountcoupon_id=obj.id).first()
            if ysh_alidiscountcoupon:
                data['user'] = ysh_alidiscountcoupon.user.nickname
                data['create_time'] = ysh_alidiscountcoupon.create_time.strftime('%Y-%m-%d %H:%M:%S')
                data['equityId'] = ysh_alidiscountcoupon.equityId
                data['type'] = ysh_alidiscountcoupon.get_type_display()
                data['sourceDistCode'] = f'{ysh_alidiscountcoupon.sourceDistCode.name}({ysh_alidiscountcoupon.sourceDistCode.code})'
                data['usageType'] = ysh_alidiscountcoupon.get_usageType_display()
                data['verifyChannel'] = ysh_alidiscountcoupon.get_verifyChannel_display()
                data['environment'] = ysh_alidiscountcoupon.environment
                data['environment_str'] = ysh_alidiscountcoupon.get_environment_display()
                data['costAmount'] = Decimal(str(ysh_alidiscountcoupon.costAmount/100))
                contract = ysh_alidiscountcoupon.contract
                if contract:
                    data['taxRate'] = contract.taxRate
                    data['supplierCode'] = contract.supplierCode
                    data['supplierName'] = contract.supplierName
                    data['contractCode'] = contract.contractCode
                    data['contractName'] = contract.contractName
        except:
            pass
        return data

    def get_is_check_identity(self, obj):
        try:
            if obj.is_check_identity == 1:
                return 1
            else:
                return 0
        except:
            return 0

    def get_is_max_number_by_day(self, obj):
        try:
            if obj.max_number_by_day:
                return 1
            else:
                return 0
        except:
            return 0

    def get_drawdown_platform(self, obj):
        try:
            return obj.drawdown_platform.platform_name
        except:
            return ''

    def get_distribution_platform(self, obj):
        try:
            return obj.distribution_platform.platform_name
        except:
            return ''

    def get_create_user(self, obj):
        try:
            return obj.user.nickname
        except:
            return ''

    def get_developer_set(self, obj):
        data = []
        try:
            developer_set = AliDiscountCouponAPIRelation.objects.filter(alidiscountcoupon_id=obj.id)
            for developer in developer_set:
                user = developer.developer
                data.append({
                    'id': developer.id,
                    'account': user.account,
                    'nickname': user.nickname
                })
        except:
            pass
        return data

    def get_can_remain_number(self, obj):
        try:
            max_number__sum = obj.alidiscountcouponlevel_set.all().aggregate(Sum('max_number'))['max_number__sum']
            if max_number__sum:
                remain_number = obj.max_number - max_number__sum
            else:
                remain_number = obj.max_number
            return remain_number
        except:
            return 0

    def get_platform(self, obj):
        try:
            platform = obj.platform
            return f'{platform.name}({platform.mchid})'
        except:
            return ''

    def get_merchant_list(self, obj):
        data = []
        try:
            alidiscountcouponmerchant_set = obj.alidiscountcouponmerchant_set.all()
            if alidiscountcouponmerchant_set:
                alidiscountcouponmerchant_set = alidiscountcouponmerchant_set[:6]
                for alidiscountcouponmerchant in alidiscountcouponmerchant_set:
                    merchant = alidiscountcouponmerchant.merchant
                    data.append(f'{merchant.short_name}({merchant.wyfMerchantID})')
        except:
            pass
        return data

    def get_publish_time(self, obj):
        try:
            return f'{obj.publish_start_time.strftime("%Y.%m.%d %H:%M:%S")}-{obj.publish_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
        except:
            return ''


class AliDiscountCouponLevelRetrieveModelSerializer(serializers.ModelSerializer):

    level_type = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    wait_number = serializers.SerializerMethodField(read_only=True)
    unclaimed_number = serializers.SerializerMethodField(read_only=True)
    can_number = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponLevel
        fields = ['id', 'level_type', 'level_name', 'max_number', 'take_number', 'remain_number', 'wait_number', 'unclaimed_number', 'use_number', 'can_number']

    def get_can_number(self, obj):
        data = {}
        data['max_number'] = 0
        data['min_number'] = 0
        try:
            activity = obj.activity
            max_number__sum = activity.alidiscountcouponlevel_set.all().aggregate(Sum('max_number'))['max_number__sum']
            if max_number__sum:
                remain_number = activity.max_number - max_number__sum
            else:
                remain_number = activity.max_number
            data['max_number'] = obj.max_number + remain_number
            data['min_number'] = obj.max_number - obj.remain_number
        except:
            pass
        return data

    def get_wait_number(self, obj):
        try:
            wait_number = obj.receive_number - obj.use_number
            return wait_number
        except:
            return ''

    def get_unclaimed_number(self, obj):
        try:
            unclaimed_number = obj.take_number - obj.receive_number
            return unclaimed_number
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_level_type(self, obj):
        try:
            level = obj.level.level
            if level == 1:
                return '省公司'
            elif level == 2:
                return '市公司'
            elif level == 3:
                return '区县'
            elif level == 4:
                return  '网点'
            else:
                return '信翔'
        except:
            return ''


class AliDiscountCouponLevelListModelSerializer(serializers.ModelSerializer):

    level_type = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    wait_number = serializers.SerializerMethodField(read_only=True)
    unclaimed_number = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    p_wait_number = serializers.SerializerMethodField(read_only=True)
    p_unclaimed_number = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponLevel
        fields = ['id', 'level_type', 'level_name', 'max_number', 'take_number', 'remain_number', 'wait_number', 'unclaimed_number', 'use_number',
                  'activity_name', 'p_max_number', 'p_take_number', 'p_remain_number', 'p_wait_number', 'p_unclaimed_number', 'p_use_number', 'common_qrcode']

    def get_wait_number(self, obj):
        try:
            wait_number = obj.receive_number - obj.use_number
            return wait_number
        except:
            return ''

    def get_p_wait_number(self, obj):
        try:
            p_wait_number = obj.p_receive_number - obj.p_use_number
            return p_wait_number
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.activity.activity_name
        except:
            return ''

    def get_unclaimed_number(self, obj):
        try:
            unclaimed_number = obj.take_number - obj.receive_number
            return unclaimed_number
        except:
            return ''

    def get_p_unclaimed_number(self, obj):
        try:
            p_unclaimed_number = obj.p_take_number - obj.p_receive_number
            return p_unclaimed_number
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_level_type(self, obj):
        try:
            level = obj.level.level
            if level == 1:
                return '省公司'
            elif level == 2:
                return '市公司'
            elif level == 3:
                return '区县'
            elif level == 4:
                return  '网点'
            else:
                return '信翔'
        except:
            return ''


class AliDiscountCouponLevelTreeModelSerializer(serializers.ModelSerializer):

    level_type = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    p_unclaimed_number = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    is_auth_str = serializers.CharField(source='get_is_auth_display', read_only=True)
    child_list = serializers.SerializerMethodField(read_only=True)
    p_wait_number = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponLevel
        fields = ['id', 'level_type', 'level_name', 'remain_number', 'activity_name',
                  'p_receive_number', 'p_remain_number', 'p_take_number', 'p_max_number', 'p_unclaimed_number', 'is_auth', 'is_auth_str',
                  'child_list', 'p_wait_number', 'p_use_number']

    def get_p_wait_number(self, obj):
        try:
            p_wait_number = obj.p_receive_number - obj.p_use_number
            return p_wait_number
        except:
            return ''

    def get_p_unclaimed_number(self, obj):
        try:
            p_unclaimed_number = obj.p_take_number - obj.p_receive_number
            return p_unclaimed_number
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.activity.activity_name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_level_type(self, obj):
        try:
            level = obj.level.level
            if level == 1:
                return '省公司'
            elif level == 2:
                return '市公司'
            elif level == 3:
                return '区县'
            elif level == 4:
                return  '网点'
            else:
                return '信翔'
        except:
            return ''

    def get_child_list(self, obj):
        level = obj.level
        if level.level == 1:
            list_queryset = AliDiscountCouponLevel.objects.filter(child_set__parent_id=obj.id, level__level=2)
            return AliDiscountCouponLevelTreeModelSerializer(list_queryset, many=True).data
        elif level.level == 2:
            list_queryset = AliDiscountCouponLevel.objects.filter(child_set__parent_id=obj.id, level__level=3)
            return AliDiscountCouponLevelTreeModelSerializer(list_queryset, many=True).data
        elif level.level == 3:
            list_queryset = AliDiscountCouponLevel.objects.filter(child_set__parent_id=obj.id, level__level=4)
            return AliDiscountCouponLevelTreeModelSerializer(list_queryset, many=True).data
        elif level.level == 4:
            return []
        else:
            return []


class AliDiscountCouponMerchantTableHistoryModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    create_user = serializers.SerializerMethodField(read_only=True)
    add_type_str = serializers.CharField(source='get_add_type_display', read_only=True)
    table_type_str = serializers.CharField(source='get_table_type_display', read_only=True)
    add_state_str = serializers.CharField(source='get_add_state_display', read_only=True)

    class Meta:
        model = AliDiscountCouponMerchantTableHistory
        fields = ('id', 'create_user', 'create_time', 'file', 'add_type', 'add_type_str', 'table_type', 'table_type_str',
                  'add_state', 'add_state_str', 'business_list', 'remark', 'file')

    def get_create_user(self, obj):
        try:
            return obj.create_user.nickname
        except:
            return ''


class AliDiscountCouponMerchantTableModelSerializer(serializers.ModelSerializer):

    white_create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    black_create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    merchant = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponMerchantTable
        fields = ('id', 'merchant', 'white_create_time', 'black_create_time', 'sub_mchid')

    def get_merchant(self, obj):
        data = {}
        data['merchant_id'] = ''
        data['merchant_name'] = ''
        data['business_no'] = ''
        data['channel_id'] = ''
        data['channel_name'] = ''
        data['merchant_short_name'] = ''
        data['level_name'] = ''
        try:
            merchant = Merchant.objects.filter(wyfMerchantID=obj.business_no).first()
            data['merchant_id'] = merchant.id
            data['merchant_name'] = merchant.name
            data['business_no'] = merchant.wyfMerchantID
            data['channel_id'] = merchant.channel_id
            data['channel_name'] = merchant.channel.name
            data['merchant_short_name'] = merchant.short_name
            data['level_name'] = merchant.level.name
        except:
            pass
        return data


class BlackTableModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    create_user = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = BlackTable
        fields = ('id', 'stock_id', 'create_time', 'create_user')

    def get_create_user(self, obj):
        try:
            return obj.create_user.nickname
        except:
            return ''


class GoodsListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    category = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    is_launched_str = serializers.CharField(source='get_is_launched_display', read_only=True)
    order_species_str = serializers.CharField(source='get_order_species_display', read_only=True)
    is_coupon_goods = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Goods
        fields = ('id', 'create_time', 'equityID', 'category', 'name', 'default_image', 'is_launched', 'is_launched_str', 'price',
                  'sales', 'remain_stock', 'merchant', 'is_coupon_goods', 'order_species', 'order_species_str')

    def get_is_coupon_goods(self, obj):
        try:
            alidiscountcoupon_id = self.context.get('alidiscountcoupon_id', None)
            if alidiscountcoupon_id:
                check_available = AliDiscountCouponGoodsAvailable.objects.filter(goods_id=obj.id, alidiscountcoupon_id=alidiscountcoupon_id)
                if check_available:
                    return 1
                else:
                    return 0
            else:
                return 0
        except:
            return 0

    def get_category(self, obj):
        try:
            return obj.category.name
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        data['name'] = ''
        data['short_name'] = ''
        data['id'] = ''
        try:
            merchant = obj.merchant
            data['name'] = merchant.name
            data['short_name'] = merchant.short_name
            data['id'] = merchant.id
        except:
            pass
        return data


class AliDiscountCouponGoodsAvailableListModelSerializer(serializers.ModelSerializer):

    goods = GoodsListModelSerializer()

    class Meta:
        model = AliDiscountCouponGoodsAvailable
        fields = ('id', 'goods')


class AliDiscountCouponSyncWYHRecordModelSerializer(serializers.ModelSerializer):

    alidiscountcoupon = serializers.SerializerMethodField(read_only=True)
    create_user = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    finish_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    sync_status_str = serializers.CharField(source='get_sync_status_display', read_only=True)

    class Meta:
        model = AliDiscountCouponSyncWYHRecord
        fields = ['id', 'alidiscountcoupon', 'create_user', 'create_time', 'finish_time', 'sync_status', 'sync_status_str', 'remark']

    def get_alidiscountcoupon(self, obj):
        data = {}
        data['activity_name'] = ''
        data['activity_id'] = ''
        try:
            alidiscountcoupon = obj.alidiscountcoupon
            data['activity_name'] = alidiscountcoupon.activity_name
            data['activity_id'] = alidiscountcoupon.id
        except:
            pass
        return data

    def get_create_user(self, obj):
        try:
            return obj.create_user.nickname
        except:
            return ''


class AliDiscountCouponDistributionPlatformModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = AliDiscountCouponDistributionPlatform
        fields = ['id', 'platform_name']


class CustomizeActivityFlipCARDSListModelSerializer(serializers.ModelSerializer):

    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    open_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    open_status_str = serializers.CharField(source='get_open_status_display', read_only=True)
    win_type_str = serializers.CharField(source='get_win_type_display', read_only=True)
    customercser_mobile = serializers.SerializerMethodField(read_only=True)
    activity_info = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityFlipCARDS
        fields = ['id', 'open_status', 'open_status_str', 'received_time', 'customercser_mobile', 'activity_info', 'open_time', 'win_type', 'win_type_str',
                  'received_time', 'open_time', 'level_name']

    def get_business_form(self, obj):
        data = {}
        try:
            if obj.customizeactivity.is_business_form == 1:
                business_form = obj.customizeactivitybusinessform
                data['business_name'] = business_form.business_name
                data['business_account'] = business_form.business_account
                data['business_amount'] = business_form.business_amount
                data['business_type'] = business_form.business_type
                data['business_type_str'] = business_form.get_business_type_display()
        except:
            pass
        return data

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_customercser_mobile(self, obj):
        try:
            return obj.mobile
        except:
            return ''

    def get_activity_info(self, obj):
        data = {}
        data['id'] = ''
        data['activity_name'] = ''
        data['activity_id'] = ''
        data['rule'] = ''
        data['amount'] = ''
        try:
            prize_type = obj.win_type
            if prize_type in [1, 2]:
                alidiscountcoupon = obj.alidiscountcoupon
                data['id'] = obj.alidiscountcouponinfo_id
                data['activity_name'] = alidiscountcoupon.activity_name
                data['activity_id'] = alidiscountcoupon.template_id
                data['rule'] = alidiscountcoupon.floor_amount
                data['amount'] = alidiscountcoupon.amount
            elif prize_type == 5:
                data['id'] = ''
                data['activity_name'] = f'{obj.point} 积分'
                data['activity_id'] = ''
                data['rule'] = f'{obj.point} 积分'
                data['amount'] = f''
            else:
                cashactivity = obj.cashactivity
                cashactivityrule_set = cashactivity.cashactivityrule_set.filter(is_delete=0).order_by('amount')
                result = ''
                for cashactivityrule in cashactivityrule_set:
                    result += f'¥{cashactivityrule.amount},'
                data['id'] = obj.cashactivitydata_id
                data['activity_name'] = cashactivity.name
                data['activity_id'] = cashactivity.activity_id
                data['rule'] = result[:-1]
                data['amount'] = obj.cashactivitydata.amount
        except:
            pass
        return data


class AliDiscountCouponInfoListModelSerializer(serializers.ModelSerializer):

    gmt_create = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_distributed = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    customeruser_realname = serializers.SerializerMethodField(read_only=True)
    companyuser_nickname = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    coupon_type = serializers.SerializerMethodField(read_only=True)
    coupon_type_str = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponInfo
        fields = ['id', 'gmt_create', 'mobile', 'status', 'status_str', 'gmt_distributed', 'customeruser_realname', 'companyuser_nickname', 'activity_name',
                  'coupon_type', 'coupon_type_str', 'level_name', 'return_msg']

    def get_mobile(self, obj):
        if obj.alidiscountcoupon.coupon_way == 5 and obj.alidiscountcoupon.coupon_channel == 1:
            return obj.login_id
        else:
            return obj.mobile

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_coupon_type_str(self, obj):
        try:
            return obj.alidiscountcoupon.get_coupon_type_display()
        except:
            return ''

    def get_coupon_type(self, obj):
        try:
            return obj.alidiscountcoupon.coupon_type
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.alidiscountcoupon.activity_name
        except:
            return ''

    def get_customeruser_realname(self, obj):
        try:
            return obj.customer_user.realname
        except:
            return ''

    def get_companyuser_nickname(self, obj):
        try:
            return obj.companyuser.nickname
        except:
            return ''


class AliDiscountCouponInfoRetrieveModelSerializer(serializers.ModelSerializer):

    gmt_use = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_distributed = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_undo = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    customeruser_realname = serializers.SerializerMethodField(read_only=True)
    activity_info = serializers.SerializerMethodField(read_only=True)
    payout_info = serializers.SerializerMethodField(read_only=True)
    customeruser_idcode = serializers.SerializerMethodField(read_only=True)
    customeruser_identification_type = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponInfo
        fields = ['id', 'mobile', 'status', 'status_str', 'customeruser_realname', 'gmt_use', 'gmt_distributed', 'gmt_undo', 'payout_info', 'activity_info', 'order_id',
                  'out_biz_order', 'user_id', 'return_msg', 'customeruser_idcode', 'customeruser_identification_type']

    def get_activity_info(self, obj):
        data = {}
        data['activity_name'] = ''
        data['floor_amount'] = ''
        data['publish_time'] = ''
        data['usetime_type'] = ''
        data['coupon_type'] = ''
        data['coupon_type_str'] = ''
        try:
            activity = obj.alidiscountcoupon
            channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
            data['coupon_type_str'] = activity.get_coupon_type_display()
            data['coupon_type'] = activity.coupon_type
            data['floor_amount'] = activity.floor_amount
            data['publish_time'] = f'{activity.publish_start_time.strftime("%Y.%m.%d %H:%M:%S")}-{activity.publish_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
            data['activity_name'] = activity.activity_name
            if channelcommonvoucher.usetime_type == 2:
                data['usetime_type'] = f'固定时间段{channelcommonvoucher.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{channelcommonvoucher.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
            elif channelcommonvoucher.usetime_type == 3:
                data['usetime_type'] = f'领取后立即生效有效时间{channelcommonvoucher.invalid_day}天'
            else:
                data['usetime_type'] = f'领取后次日凌晨生效有效时间{channelcommonvoucher.invalid_day}天'
            if channelcommonvoucher.join_limit_by_user == 1:
                data['join_limit_by_user'] = f'活动期间每个用户可参与{channelcommonvoucher.join_limit_by_user_count}次'
            else:
                data['join_limit_by_user'] = '不限制'
            if channelcommonvoucher.join_limit_by_bay == 1:
                data['join_limit_by_bay'] = f'每个用户每日可参与{channelcommonvoucher.join_limit_by_bay_count}次'
            if channelcommonvoucher.join_limit_by_bay == 2:
                data['join_limit_by_bay'] = f'每个用户每月可参与{channelcommonvoucher.join_limit_by_bay_count}次'
            elif channelcommonvoucher.join_limit_by_bay == 4:
                data['join_limit_by_bay'] = f'每个用户每周可参与{channelcommonvoucher.join_limit_by_bay_count}次'
            else:
                data['join_limit_by_bay'] = '不限制'
        except:
            pass
        return data

    def get_payout_info(self, obj):
        data = {}
        data['alidiscountcoupon_id'] = ''
        data['level_name'] = ''
        data['companyuser_nickname'] = ''
        data['gmt_create'] = ''
        try:
            data['alidiscountcoupon_id'] = obj.alidiscountcoupon_id
            data['companyuser_nickname'] = obj.companyuser.nickname
            data['gmt_create'] = obj.gmt_create.strftime("%Y-%m-%d %H:%M:%S")
            data['level_name'] = obj.level.name
        except:
            pass
        return data

    def get_customeruser_realname(self, obj):
        try:
            if obj.customer_user:
                return obj.customer_user.realname
            else:
                return obj.customeruservice.realname
        except:
            return ''

    def get_customeruser_idcode(self, obj):
        try:
            if obj.customer_user:
                idcode = obj.customer_user.idcode
            else:
                idcode = obj.customeruservice.idcode
            return f'{idcode[:5]}****{idcode[-4:]}'
        except:
            return ''

    def get_customeruser_identification_type(self, obj):
        try:
            if obj.customer_user:
                return obj.customer_user.get_identification_type_display()
            else:
                return obj.customeruservice.get_identification_type_display()
        except:
            return ''


class CustomizeActivityFlipCARDSRetrieveModelSerializer(serializers.ModelSerializer):

    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    open_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    open_status_str = serializers.CharField(source='get_open_status_display', read_only=True)
    win_type_str = serializers.CharField(source='get_win_type_display', read_only=True)
    customercser_mobile = serializers.SerializerMethodField(read_only=True)
    activity_info = serializers.SerializerMethodField(read_only=True)
    activity_detail = serializers.SerializerMethodField(read_only=True)
    level = serializers.SerializerMethodField(read_only=True)
    business_form = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityFlipCARDS
        fields = ['id', 'open_status', 'open_status_str', 'received_time', 'customercser_mobile', 'activity_info', 'open_time', 'win_type', 'win_type_str',
                  'received_time', 'open_time', 'level', 'business_form', 'return_msg', 'activity_detail']

    def get_activity_detail(self, obj):
        data = []
        if obj.win_type == 8:
            detail_set = CustomizeActivityFlipCARDSDetail.objects.filter(flipcard_id=obj.id)
            for detail in detail_set:
                data.append(AliDiscountCouponInfoListModelSerializer(detail.alidiscountcouponinfo).data)
        return data

    def get_business_form(self, obj):
        data = {}
        try:
            if obj.customizeactivity.is_business_form == 1:
                business_form = obj.customizeactivitybusinessform
                data['business_name'] = business_form.business_name
                data['business_account'] = business_form.business_account
                data['business_amount'] = business_form.business_amount
                data['business_type'] = business_form.business_type
                data['business_type_str'] = business_form.get_business_type_display()
        except:
            pass
        return data

    def get_level(self, obj):
        data = {}
        data['city_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        try:
            level = obj.level
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
        except:
            pass
        return data

    def get_customercser_mobile(self, obj):
        try:
            if obj.user:
                mobile = obj.user.mobile
                return mobile
            else:
                mobile = obj.customeruservice.customeruser.mobile
                return mobile
        except:
            return ''

    def get_activity_info(self, obj):
        data = {}
        data['id'] = ''
        data['activity_name'] = ''
        data['activity_id'] = ''
        data['rule'] = ''
        data['amount'] = ''
        try:
            prize_type = obj.win_type
            if prize_type in [1, 2]:
                alidiscountcoupon = obj.alidiscountcoupon
                data['id'] = obj.alidiscountcouponinfo_id
                data['activity_name'] = alidiscountcoupon.activity_name
                data['activity_id'] = alidiscountcoupon.template_id
                data['rule'] = alidiscountcoupon.floor_amount
                data['amount'] = alidiscountcoupon.amount
            elif prize_type == 5:
                data['id'] = ''
                data['activity_name'] = f'{obj.point} 积分'
                data['activity_id'] = ''
                data['rule'] = f'{obj.point} 积分'
                data['amount'] = f''
            else:
                cashactivity = obj.cashactivity
                cashactivityrule_set = cashactivity.cashactivityrule_set.filter(is_delete=0).order_by('amount')
                result = ''
                for cashactivityrule in cashactivityrule_set:
                    result += f'¥{cashactivityrule.amount},'
                data['id'] = obj.cashactivitydata_id
                data['activity_name'] = cashactivity.name
                data['activity_id'] = cashactivity.activity_id
                data['rule'] = result[:-1]
                data['amount'] = obj.cashactivitydata.amount
        except:
            pass
        return data


class UpdateStockUsableMerchantListModelSerializer(serializers.ModelSerializer):

    user_nickname = serializers.SerializerMethodField(read_only=True)
    remark = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    wx_is_enter_str = serializers.CharField(source='get_wx_is_enter_display', read_only=True)
    ylx_is_enter_str = serializers.CharField(source='get_wx_is_enter_display', read_only=True)
    apply_state_str = serializers.CharField(source='get_apply_state_display', read_only=True)

    class Meta:
        model = UpdateStockUsableMerchant
        fields = ['id', 'user_nickname', 'file', 'remark', 'create_time', 'wx_is_enter', 'wx_is_enter_str', 'ylx_is_enter', 'ylx_is_enter_str',
                  'max_number', 'wx_entry_number', 'ylx_entry_number', 'apply_state', 'apply_state_str', 'logs_file']

    def get_remark(self, obj):
        if obj.apply_state == 3:
            return obj.return_msg
        else:
            return obj.remark

    def get_user_nickname(self, obj):
        try:
            return obj.user.nickname
        except:
            return ''


class UpdateStockUsableMerchantRetrieveModelSerializer(serializers.ModelSerializer):

    user_nickname = serializers.SerializerMethodField(read_only=True)
    remark = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    wx_is_enter_str = serializers.CharField(source='get_wx_is_enter_display', read_only=True)
    ylx_is_enter_str = serializers.CharField(source='get_wx_is_enter_display', read_only=True)
    apply_state_str = serializers.CharField(source='get_apply_state_display', read_only=True)
    alidiscountcoupon = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = UpdateStockUsableMerchant
        fields = ['id', 'user_nickname', 'file', 'remark', 'create_time', 'wx_is_enter', 'wx_is_enter_str', 'ylx_is_enter', 'ylx_is_enter_str',
                  'max_number', 'wx_entry_number', 'ylx_entry_number', 'apply_state', 'apply_state_str', 'alidiscountcoupon', 'line_number']

    def get_alidiscountcoupon(self, obj):
        data = {}
        data['alidiscountcoupon_id'] = ''
        data['activity_name'] = ''
        data['floor_amount'] = ''
        data['amount'] = ''
        data['transaction_minimum'] = ''
        try:
            alidiscountcoupon = obj.alidiscountcoupon
            data['alidiscountcoupon_id'] = alidiscountcoupon.id
            data['activity_name'] = alidiscountcoupon.activity_name
            data['floor_amount'] = alidiscountcoupon.floor_amount
            data['amount'] = alidiscountcoupon.amount
            data['transaction_minimum'] = alidiscountcoupon.transaction_minimum
        except:
            pass
        return data

    def get_remark(self, obj):
        if obj.apply_state == 3:
            return obj.return_msg
        else:
            return obj.remark

    def get_user_nickname(self, obj):
        try:
            return obj.user.nickname
        except:
            return ''


class MerchantListModelSerializer(serializers.ModelSerializer):

    subject_type_str = serializers.CharField(source='get_subject_type_display', read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_mall_str = serializers.CharField(source='get_is_mall_display', read_only=True)
    applyment_state_str = serializers.CharField(source='get_applyment_state_display', read_only=True)
    verify_state_str = serializers.CharField(source='get_verify_state_display', read_only=True)
    is_enter_auth = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Merchant
        fields = ('id', 'level_name', 'subject_type_str', 'subject_type', 'name', 'wyfMerchantID', 'branch_num',
                  'order_num', 'settlement_amount', 'create_time', 'short_name', 'settlement_amount_by_day',
                  'is_mall', 'is_mall_str', 'applyment_state', 'applyment_state_str', 'verify_state', 'verify_state_str',
                  'is_enter_auth')

    def get_is_enter_auth(self, obj):
        if obj.is_mall == 0:
            if obj.channel_id != 3:
                return 0
            else:
                return 1
        else:
            return 0

    def get_level_name(self, obj):
        try:
            if obj.applyment_state in [1, 4]:
                mall_applyment = MerchantMallApplyment.objects.filter(merchant_id=obj.id, applyment_type=1).last()
                if mall_applyment:
                    if mall_applyment.applyment_state == 4:
                        result = check_sign_contract_result(obj.ruiyinxinMerchantID)
                        if result['data']['sign_status'] == 3:
                            obj.applyment_state = 1
                            obj.verify_state = 1
                            obj.save()
                            mall_applyment.applyment_state = 1
                            mall_applyment.audit_time = datetime.datetime.now()
                            mall_applyment.save()
                    elif mall_applyment.applyment_state == 1:
                        result = get_sign_contract_url(obj.ruiyinxinMerchantID)
                        if result['result_code'] != 'fail':
                            if result['data']['open_status'] == 2:
                                if not mall_applyment.sign_url:
                                    signUrl = result['data']['signUrl']
                                    sign_url = make_qrcode1(obj.ruiyinxinMerchantID, signUrl, key=None)
                                    mall_applyment.sign_url = sign_url
                                mall_applyment.applyment_state = 2
                                mall_applyment.save()
                                obj.applyment_state = 2
                                obj.save()
                            elif result['data']['open_status'] == 3:
                                mall_applyment.applyment_state = 3
                                mall_applyment.reject_reason = result['data']['open_result']
                                mall_applyment.save()
                                obj.applyment_state = 3
                                obj.save()
        except:
            pass
        try:
            return obj.level.name
        except:
            return ''


class AliDiscountCouponMerchantModelSerializer(serializers.ModelSerializer):

    merchant = MerchantListModelSerializer()
    channel = serializers.SerializerMethodField(read_only=True)
    # last_update_time = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponMerchant
        fields = ['id', 'sub_mchid', 'merchant', 'channel_id', 'channel']

    def get_channel(self, obj):
        try:
            return obj.channel.name
        except:
            return ''


class CustomizeActivityListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_begin_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_status_str = serializers.CharField(source='get_activity_status_display', read_only=True)
    activity_type_str = serializers.CharField(source='get_activity_type_display', read_only=True)
    prize_type_str = serializers.SerializerMethodField(read_only=True)
    prize_type_array = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivity
        fields = ['id', 'create_time', 'activity_status', 'activity_status_str', 'available_begin_time', 'available_end_time',
                  'activity_type', 'activity_type_str', 'prize_type_str', 'prize_type', 'activity_name', 'level_name', 'join_user_count',
                  'prize_type_array']

    def get_prize_type_array(self, obj):
        data = []
        try:
            PRIZE_TYPE_CHOICES = {
                "1": {"prize_type": 1, "prize_type_str": "支付宝代金券"},
                "2": {"prize_type": 2, "prize_type_str": "微信代金券"},
                "3": {"prize_type": 3, "prize_type_str": "微信鼓励金"},
                "5": {"prize_type": 5, "prize_type_str": "积分"},
                "6": {"prize_type": 6, "prize_type_str": "支付宝鼓励金"},
                "7": {"prize_type": 7, "prize_type_str": "商家券"},
                "8": {"prize_type": 8, "prize_type_str": "美团代金券"},
            }
            prize_type = obj.prize_type
            for key,value in PRIZE_TYPE_CHOICES.items():
                if key in prize_type:
                    data.append(value)
        except:
            pass
        return data

    def get_prize_type_str(self, obj):
        try:
            data = obj.prize_type.replace('1', '支付宝代金券').replace('2', '微信代金券').replace('3', '微邮惠礼包')
            return data
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''


class CustomizeActivityRulesListModelSerializer(serializers.ModelSerializer):

    prize_type_str = serializers.CharField(source='get_prize_type_display', read_only=True)
    activity_info = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityRules
        fields = ['id', 'prize_type', 'prize_type_str', 'activity_info', 'count']

    def get_activity_info(self, obj):
        data = {}
        data['id'] = ''
        data['activity_name'] = ''
        data['activity_id'] = ''
        data['rule'] = ''
        data['available_begin_time'] = ''
        data['available_end_time'] = ''
        data['max'] = ''
        data['remain'] = ''
        data['take'] = ''
        try:
            prize_type = obj.prize_type
            if prize_type in [1, 2, 7, 8]:
                alidiscountcoupon = obj.alidiscountcoupon
                data['id'] = alidiscountcoupon.id
                data['activity_name'] = alidiscountcoupon.activity_name
                data['activity_id'] = alidiscountcoupon.template_id
                data['rule'] = alidiscountcoupon.floor_amount
                data['available_begin_time'] = alidiscountcoupon.publish_start_time.strftime("%Y-%m-%d %H:%M:%S")
                data['available_end_time'] = alidiscountcoupon.publish_end_time.strftime("%Y-%m-%d %H:%M:%S")
                data['max'] = alidiscountcoupon.max_number
                data['remain'] = alidiscountcoupon.remain_number
                data['take'] = alidiscountcoupon.send_count
            else:
                cashactivity = obj.cashactivity
                cashactivityrule_set = cashactivity.cashactivityrule_set.filter(is_delete=0).order_by('amount')
                result = ''
                for cashactivityrule in cashactivityrule_set:
                    result += f'¥{cashactivityrule.amount},'
                data['id'] = cashactivity.id
                data['activity_name'] = cashactivity.name
                data['activity_id'] = cashactivity.activity_id
                data['rule'] = result[:-1]
                data['available_begin_time'] = cashactivity.available_begin_time.strftime("%Y-%m-%d %H:%M:%S")
                data['available_end_time'] = cashactivity.available_end_time.strftime("%Y-%m-%d %H:%M:%S")
                data['max'] = cashactivity.max_amount
                data['remain'] = cashactivity.remain_amount
                data['take'] = cashactivity.take_amount
        except:
            pass
        return data


class CustomizeActivityRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_begin_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    activity_status_str = serializers.CharField(source='get_activity_status_display', read_only=True)
    activity_type_str = serializers.CharField(source='get_activity_type_display', read_only=True)
    is_need_auth_str = serializers.CharField(source='get_is_need_auth_display', read_only=True)
    is_white_str = serializers.CharField(source='get_is_white_display', read_only=True)
    prize_type_str = serializers.SerializerMethodField(read_only=True)
    level = serializers.SerializerMethodField(read_only=True)
    customizeactivityrules_set = CustomizeActivityRulesListModelSerializer(many=True)
    prize_type_array = serializers.SerializerMethodField(read_only=True)
    drawdown_platform_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivity
        fields = ['id', 'create_time', 'activity_status', 'activity_status_str', 'available_begin_time', 'available_end_time',
                  'activity_type', 'activity_type_str', 'prize_type_str', 'prize_type', 'activity_name', 'level', 'join_user_count',
                  'is_need_auth', 'is_need_auth_str', 'lucky_count_by_user', 'activity_description', 'customizeactivityrules_set',
                  'is_white', 'is_white_str', 'prize_type_array', 'max_number', 'take_number', 'remain_number', 'drawdown_platform_id',
                  'drawdown_platform_name']

    def get_drawdown_platform_name(self, obj):
        try:
            return obj.drawdown_platform.platform_name
        except:
            return ''

    def get_prize_type_array(self, obj):
        data = []
        try:
            PRIZE_TYPE_CHOICES = {
                "1": {"prize_type": 1, "prize_type_str": "支付宝代金券"},
                "2": {"prize_type": 2, "prize_type_str": "微信代金券"},
                "3": {"prize_type": 3, "prize_type_str": "微信鼓励金"},
                "5": {"prize_type": 5, "prize_type_str": "积分"},
                "6": {"prize_type": 6, "prize_type_str": "支付宝鼓励金"},
                "7": {"prize_type": 7, "prize_type_str": "商家券"},
                "8": {"prize_type": 8, "prize_type_str": "美团代金券"},
            }
            prize_type = obj.prize_type
            for key,value in PRIZE_TYPE_CHOICES.items():
                if key in prize_type:
                    data.append(value)
        except:
            pass
        return data

    def get_prize_type_str(self, obj):
        try:
            data = obj.prize_type.replace('1', '支付宝代金券').replace('2', '微信代金券').replace('3', '微邮惠礼包')
            return data
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': '',
            'account': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account'] = level.account
            return data
        except:
            return data


class CustomizeActivityLevelListModelSerializer(serializers.ModelSerializer):

    level_type = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityLevel
        fields = ['id', 'level_type', 'level_name', 'activity_name', 'max_number', 'take_number', 'remain_number', 'receive_number']

    def get_activity_name(self, obj):
        try:
            return obj.customizeactivity.name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_level_type(self, obj):
        try:
            level = obj.level.level
            if level == 1:
                return '省公司'
            elif level == 2:
                return '市公司'
            elif level == 3:
                return '区县'
            elif level == 4:
                return  '网点'
            else:
                return '信翔'
        except:
            return ''